package cn.five.stream.audio;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

public class RecorderInterface {
	private  AudioRecord audioRecord;
	private static RecorderInterface mRecorderInterface;
	private static boolean isRecording=false;
	
	private int audioSource=MediaRecorder.AudioSource.MIC;
	private int sampleRateInHz=44100;
	private int channelConfig=AudioFormat.CHANNEL_CONFIGURATION_STEREO;
	private int audioFormat=AudioFormat.ENCODING_PCM_16BIT;
	private int bufferSizeInBytes;
	private byte[] audioData;
	private Thread thread=null;
	
	/**
	 * 获取单例
	 * @return
	 */
	public static synchronized RecorderInterface getInstance(){
		if(mRecorderInterface == null){
			mRecorderInterface = new RecorderInterface();
		}
		return mRecorderInterface;
	}
	/**
	 * 设置录音机参数
	 * @param audioSource
	 * @param sampleRateInHz
	 * @param channelConfig
	 * @param audioFormat
	 */
	public void setRecorderParameters(int audioSource,int sampleRateInHz,int channelConfig,int audioFormat){
		if (audioSource>0) {
			this.audioSource=audioSource;
		}
		if (sampleRateInHz>0) {
			this.sampleRateInHz=sampleRateInHz;
		}
		if (channelConfig>0) {
			this.channelConfig=channelConfig;
		}
		if (audioFormat>0) {
			this.audioFormat=audioFormat;
		}
		
	}
	/**
	 * 获取录音机状态
	 * @return
	 */
	public static boolean isRecording() {
		return isRecording;
	}
	/**
	 * 启动录音机
	 */
	public void doStartAudioRecord(final DeviceInterface device){
		doStopRecorder();
		bufferSizeInBytes=AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
    	audioRecord=new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes);
    	audioData=new byte[bufferSizeInBytes];
    	audioRecord.startRecording();
    	isRecording=true;
    	if (thread!=null) {
			thread=null;
		}
    	thread=new Thread(new Runnable() {
			@Override
			public void run() {
				while (isRecording){
					int bufferReadResult = audioRecord.read(audioData, 0, bufferSizeInBytes); 
					if (bufferReadResult>0) {
						device.encodeAndSendData(audioData);
					}
					try {
						Thread.sleep(3);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
			}
		});
    	thread.start();
	}
	/**
	 * 停止录音机
	 */
	public synchronized void doStopRecorder(){
		isRecording=false;
		if (audioRecord!=null) {
			if (thread!=null) {
				thread.interrupted();
				thread.isInterrupted();
				thread=null;
			}
			audioRecord.release();
			audioRecord=null;
		}
	}

}
